package net.huadong.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * NIO 服务线程
 */
public class MultiplexerTimeServer implements Runnable {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop = false;

    public MultiplexerTimeServer(int port) {
        try {
            selector = Selector.open();//创建多路复用器
            serverSocketChannel = ServerSocketChannel.open();//创建通道监听客户端
            serverSocketChannel.configureBlocking(false);//设置为非阻塞模式
            serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);//绑定监听端口
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//将通道注册到多路复用器中，并监听ACCEPT事件
            System.out.println("服务启动，端口为：" + port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                selector.select(1000);//监听客户端请求，阻塞1000毫秒
                Set<SelectionKey> selectionKeys = selector.selectedKeys();//轮训key
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                //如果坚挺到key
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();
                    try {
                        handleInput(key);//处理key
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.exit(1);
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
                if (selector != null) {
                    try {
                        selector.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * key 消息处理
     * @param key
     * @throws IOException
     */
    private void handleInput(SelectionKey key) throws IOException {
        //key是否有效
        if (key.isValid()) {
            //接收请求
            if (key.isAcceptable()) {
                //接收到客户端连接请求之后，获取通道，注册状态为read
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                //同意客户端接入请求
                SocketChannel sc = ssc.accept();
                //设置客户端链路为非阻塞
                sc.configureBlocking(false);
                //将通道注册到多路复用器上，监听状态为read读信息
                sc.register(selector, SelectionKey.OP_READ);

            }
            //通道已经准备好读取
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);//ByteBuffer解码
                int readBytes = sc.read(byteBuffer);
                if (readBytes > 0) {
                    byteBuffer.flip();
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    byteBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("服务端接收到指令:" + body);
                    if ("QUERY_TIME_ORDER".equals(body)) {
                        doWrite(sc, new Date(System.currentTimeMillis()).toString());
                    } else {
                        doWrite(sc, "BAD ORDER");
                    }
                } else if (readBytes < 0) {
                    key.channel();
                    sc.close();
                } else {

                }
            }
        }
    }

    /**
     * 写入回执信息
     * @param channel
     * @param response
     * @throws IOException
     */
    private void doWrite(SocketChannel channel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
            byteBuffer.put(bytes);
            byteBuffer.flip();
            channel.write(byteBuffer);
        }
    }

}
